<?php
/**
 * 叶华盛
 * User: 自定义函数
 * Date: 2017/8/9
 * Time: 17:52
 */
use core\Router;
use core\Redis;
/**
 * 处理中文json格式
 * @param array $data
 * @return bool|string
 */
function json_encode_cn( $data=array() )
{
    if( empty($data) ) return false;

    if( (version_compare(PHP_VERSION, '5.4.0') >= 0) )
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    else
        return urldecode( json_encode(urlencode_array($data)) );
}

/**
 * 将数组中的中文转义
 * @param array $data
 * @return array|bool
 */
function urlencode_array( $data=array() )
{
    if( empty( $data ) ) return false;
    foreach( $data as $key=>$val )
    {
        if( is_array( $val ) )
            $data[$key] =   urlencode_array( $val );
        else
        {
            if( is_string($val) )
                $data[$key] =   urlencode($val);
        }
    }
    return $data;
}

/**
 * 调试参数
 */
function p()
{
    for( $i=0; $i < func_num_args(); $i++ )
    {
        echo '<pre>';
        $param  =   func_get_arg( $i );
        if( is_array( $param ) )
            print_r( $param );
        elseif ( is_object($param) || is_int($param) || is_null( $param ) || is_bool( $param ) )
            var_dump( $param );
        else
            echo $param;
        echo '</pre>';
    }
}

/**
 * 生成超链接
 * @param string $url
 * @param null $param
 * @return string
 */
function U($url='',$param=null)
{
    if( empty( $url ) )
        $url    =   '/';
    else
        $url    =   Router::createUrl($url,$param);
    return $url;
}

/**
 * @param $key
 * @param null $val
 * @param int $expire
 * @return mixed
 */
function M($key,$val=null,$expire=0)
{
    $redisObj   =   new Redis();
    if( $val!==null )
        $res    =   $redisObj->set($key,$val,$expire);
    else
        $res    =   $redisObj->get($key);
    return  $res;
}

/**
 * 获取ip
 * @return string
 */
function getIp()
{
    $realip = '';
    $unknown = 'unknown';
    if (isset($_SERVER)){
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach($arr as $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                    break;
                }
            }
        }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
            $realip = $_SERVER['REMOTE_ADDR'];
        }else{
            $realip = $unknown;
        }
    }else{
        if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
            $realip = getenv("HTTP_CLIENT_IP");
        }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
            $realip = getenv("REMOTE_ADDR");
        }else{
            $realip = $unknown;
        }
    }
    $realip = preg_match('/[\d\.]{7,15}/i', $realip, $matches) ? $matches[0] : $unknown;
    return $realip;
}

/**
 * curl请求
 * @param $url
 * @param string $method
 * @param string $data
 * @param int $timeout
 * @param array $header
 * @param array $other_curlopt
 * @param bool|false $has_cookie
 * @param string $proxy
 * @return mixed
 */
function httpCurl($url,$method='get',$data='',$timeout=120,$header=array(),$other_curlopt=array(),$has_cookie=false,$proxy='')
{
    $method =   strtolower($method);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;

    //设置默认头部
    $default_header =   array(
        'Pragma'        =>  'no-cache',
        'Cache-Control' =>  'no-cache',
        'Connection'    =>  'close'
    );
    //把头部并接起来
    if( !empty( $header ) )
        $default_header =   array_merge($default_header,$header);

    $set_header =   array();
    foreach( (array)$default_header as $k=>$v )
        $set_header[]   =   $k.':'.$v;

    //初始化cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);//请求的url
    curl_setopt($ch, CURLOPT_HEADER, 0);//是否显示返回头部信息
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否使用文件流方式返回
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);//设置curl允许执行的最长秒数
    switch($method)
    {
        case 'post':
            curl_setopt($ch, CURLOPT_POST, true);//是否post请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data)?http_build_query($data):$data);//请求post的参数
            break;
        case 'get':
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            break;
        case 'put':
            curl_setopt($ch, CURLOPT_PUT, true);
            break;
        case 'delete':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
    }
    //添加头部请求
    curl_setopt($ch, CURLOPT_HTTPHEADER, $set_header);

    //检查是否https
    if ($SSL)
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    curl_setopt($ch, CURLOPT_HTTP_VERSION, '1.1');//http协议的版本

    //设置其他curl参数
    if( !empty( $other_curlopt ) )
    {
        foreach( (array)$other_curlopt as $k=>$v )
            curl_setopt($ch, $k, $v);
    }
    //是否使用cookie请求
    if( $has_cookie )
    {
        $file_cookie    =   ROOT.DS.'webroot'.DS.'curl_cookie'.DS.'cookie.txt';
        if( !file_exists( $file_cookie ) )
        {
            $fopen  =   fopen($file_cookie,'wb');
            fclose($fopen);
        }
        curl_setopt($ch, CURLOPT_COOKIEFILE, $file_cookie);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $file_cookie);
    }

    //启用代理
    if( !empty( $proxy ) )
        curl_setopt ($ch, CURLOPT_PROXY, $proxy);

    $content    =   curl_exec($ch);
    curl_close($ch);
    return $content;
}